import { message, downLoadFile, nextDownLoad } from "./util.js";

export const parse = (content: string) => {
  // 1 判断类型
  if (typeof content !== 'string') {
    return message.error("请输入字符串格式!")
  }
  // 2 转换格式
  const arrs = content.split("\n")
  // 3 遍历提取
  let str = ""
  arrs.forEach((v, i) => {
    switch (i) {
      case 0:
        str += `${v.replace(/\[\d{4}\]/g, "")}`
        break
      case 1:
        str += ` ${v} `
        break
      case 2:
        let _matchStr = v
        let count = 0
        let _matchIndex = 0
        let startIndex = 0
        while (count < 3) {
          count++;
          _matchIndex = _matchStr.indexOf(" ")
          str += _matchStr.substring(startIndex, _matchIndex)
          _matchStr = _matchStr.substring(_matchIndex + 1)
          startIndex = startIndex
        }
        str += ` ${_matchStr.replace(/\[\d{4}\]/g, "")}`
        break
      default:
        break
    }
  })
  return str
}

export const parseHtml = async (html: string) => {
  // 1 设置节点
  const originDom = document.createElement("div")
  originDom.innerHTML = html

  // 2.1 提取商详视频(如果存在)
  const videoDom = originDom.querySelector(".detail-video-wrapper video.lib-video")
  // 2.2 提取商详数组
  let detailImgUrls: string[] = []
  const imgList = [...originDom.querySelectorAll(".img-list-wrapper > .detail-gallery-turn-wrapper")]
  if (videoDom) imgList.splice(0, 1)
  imgList.forEach(dom => detailImgUrls.push(dom.querySelector("img")?.getAttribute("src") || ""))
  // 2.3 提取 SKU 数组（单规格 | 多规格需要自己改名）
  let skuImgUrls: string[] = []
  const skuList = [...originDom.querySelectorAll(".sku-item-image")]
  const skuLen = skuList.length
  skuList.forEach(dom => skuImgUrls.push((dom as HTMLDivElement).style.background?.match(/\"([^"]+)\"/)?.[1] || ""))
  if (!skuLen) {
    // 多规格情况
    const propsList = [...originDom.querySelectorAll('.prop-item')]
    if (propsList.length) {
      const detailLen = detailImgUrls.length
      skuImgUrls.push(...detailImgUrls.slice(detailLen - propsList.length, detailLen))
    }
  }
  detailImgUrls = detailImgUrls.slice(0, detailImgUrls.length - skuImgUrls.length)
  // 2.4 提取商品描述
  const descriptImgUrls: string[] = []
  const descripts = [...originDom.querySelectorAll(".content-detail img")]
  descripts.forEach(dom => descriptImgUrls.push(dom.getAttribute("data-lazyload-src") || ""))

  // 3 下载资源
  if (videoDom) {
    const videoUrl = videoDom.getAttribute("src")
    videoUrl && await downLoadFile(videoUrl, "video")
    message.success("商详视频下载完成")
  }
  nextDownLoad(detailImgUrls, i => `detail-${i + 1}`, () => {
    message.success("商详图片下载完成")
    nextDownLoad(skuImgUrls, i => `sku-${i + 1}`, () => {
      message.success("SKU图片下载完成")
      nextDownLoad(descriptImgUrls, i => `desc-${i + 1}`, () => {
        message.success("商品详细图下载完成")
      })
    })
  })
}
